package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Category;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class ViewItemServlet extends HttpServlet {
    private String itemId;
    private LogService logService;
    private Account account;
    private Product product;
    public static final String VIEW_ITEM = "/WEB-INF/jsp/catalog/Item.jsp";
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        itemId = request.getParameter("itemId");
        CatalogService service = new CatalogService();
        Item item = service.getItem(itemId);
        List<Item> itemList = service.getItemListByProduct(itemId);
        String productId = service.getProductID(itemId);
        Product product = service.getProduct(productId);
        HttpSession session = request.getSession();
        account = (Account)session.getAttribute("account");
        if (account != null){
            logService = new LogService();
            logService.insertLog("View Item","Item:"+itemId, account.getUsername());
        } else {
            logService = new LogService();
            logService.insertLog("View Item","Item:"+itemId, "null");
        }

        session.setAttribute("item",item);
        session.setAttribute("itemList",itemList);
        session.setAttribute("product",product);


        request.getRequestDispatcher(VIEW_ITEM).forward(request,response);
    }
}
